import java.lang.System;

/**
 * 合并有序数组
 *
 * 输⼊:
 * nums1 = [1,2,3,0,0,0], m = 3
 * nums2 = [2,5,6], n = 3
 * 输出: [1,2,2,3,5,6]
 */
public class MergeOrderedArray {

    public void solution(int[] nums1, int m, int[] nums2, int n) {
        int index1 = m -1, index2 = n - 1;
        int indexMerge = m + n -1;

        while (index1 >= 0 || index2 >= 0) {
            if (index1 < 0) {
                nums1[indexMerge--] = nums2[index2--];
            } else if (index2 < 0) {
                nums1[indexMerge--] = nums1[index1--];
            } else if (nums1[index1] > nums2[index2]) {
                nums1[indexMerge--] = nums1[index1--];
            } else {
                nums1[indexMerge--] = nums2[index2--];
            }
        }
    }

    public static void main(String[] args) {
        int[] arr1 = new int[]{1,2,3,0,0,0};
        int[] arr2 = new int[]{2,5,6};
        new MergeOrderedArray().solution(arr1, 3, arr2, arr2.length);
        System.out.println("arr1: ");
        for (int item: arr1) {
            System.out.print(item + ", ");
        }
        System.out.println("\narr2: ");
        for (int item: arr2) {
            System.out.print(item + ", ");
        }
    }
}